"""
题目描述：手动实现一个简单的线程池类，包含初始化、提交任务和关闭方法。使用该线程池计算 1-100 的平方和、立方和，并分别打印结果。
评分标准：
正确管理工作线程（10 分）
任务队列实现（10 分）
提交和执行机制（10 分）
正确计算结果（10 分）
"""
import threading
import queue
class ThreadPool:
    def __init__(self, num_threads):
        self.task_queue = queue.Queue()
        self.workers = []
        self._stop_event = threading.Event()
        for _ in range(num_threads):
            worker = threading.Thread(target=self._worker_loop)
            worker.daemon = True
            worker.start()
            self.workers.append(worker)
    def _worker_loop(self):
        while not self._stop_event.is_set():
            try:
                task, args, kwargs = self.task_queue.get(timeout=1)
                task(*args, **kwargs)
                self.task_queue.task_done()
            except queue.Empty:
                continue
    def submit(self, task, *args, **kwargs):
        self.task_queue.put((task, args, kwargs))
    def shutdown(self):
        self._stop_event.set()
        for worker in self.workers:
            worker.join(timeout=1)
# 使用线程池计算平方和和立方和
results = []
lock = threading.Lock()
def sum_squares(start, end):
    total = sum(x * x for x in range(start, end + 1))
    with lock:
        results.append(total)
def sum_cubes(start, end):
    total = sum(x * x * x for x in range(start, end + 1))
    with lock:
        results.append(total)
pool = ThreadPool(2)
pool.submit(sum_squares, 1, 100)
pool.submit(sum_cubes, 1, 100)
pool.shutdown()

print("平方和:", results[0])
print("立方和:", results[1])